<template>
	<loading v-if="isLoading" style="height: 70vh;"></loading>
	<view class="tn-flex tn-flex-column" v-else>
		<view class="tn-flex tn-mb">
			<tn-button type="warning" class="tn-mr" @click="btns('clear')">清理</tn-button>
			<tn-button type="danger" @click="btns('reload')">重载</tn-button>
		</view>
		<view class="tn-radius card_item tn-p-sm tn-w-full" v-for="item in periodicList" :key="item.id"
			@click.stop="openPopup(item)">
			<view class="tn-flex items-center justify-between">
				<view class="tn-flex items-center">
					<tn-title :title="item.cycle_name" mode="hLine" assist-color="tn-blue" size="lg" />
					<tn-icon name="pushpin-fill" type="primary" class="tn-ml-xs" offset-top="-2rpx" />
				</view>
				<tn-switch @change="changeActiveSwitch($event,'is_default',item)" v-model="item.is_default" size="sm"
					:active-value="1" :inactive-value="0" active-text="默认" inactive-text="关闭" />
			</view>
			<view class="tn-flex tn-flex-column justify-around tn-mt-sm">
				<text class="tn-mt-xs">
					<text>周期比例：</text>
					<text class="tn-text-sm">{{item.cycle_rate}}%</text>
				</text>
				<text class="tn-mt-xs">
					<text>周期天数：</text>
					<text class="tn-text-sm">{{item.cycle_value}}天</text>
				</text>
				<text class="tn-mt-xs">
					<text>描述信息：</text>
					<text class="tn-text-sm">{{item.cycle_desc}}</text>
				</text>
			</view>
			<view class="tn-flex justify-between items-center tn-pt-sm tn-mt-sm tn-border-top tn-gray-light_border">
				<view class="tn-flex items-center">
					<tn-switch @change="changeActiveSwitch($event,'status',item)" v-model="item.status" size="sm"
						shape="square" :active-value="1" :inactive-value="0" active-text="启用" active-color="tn-green"
						inactive-text="禁用" />
				</view>

				<view class="tn-flex items-center">
					<text class="tn-mr-xs tn-text-xs tn-type-info_text">编辑配置</text>
					<tn-icon name="right" size="26" />
				</view>
			</view>
		</view>
	</view>
	<tn-modal ref="modalRef" />
	<tn-popup v-model="showPopup" open-direction="bottom">
		<view class="tn-p-lg tn-pt-sm">
			<view class="tn-flex-center-center tn-text-lg tn-mb-sm">
				编辑周期配置
			</view>
			<tn-form :model="config" ref="formRef" :rules="formRules" label-position="top">
				<tn-form-item label="账期" prop="cycle_value">
					<tn-input v-model="config.cycle_value" type="digit" placeholder="请输入账期（天数）" clearable
						@input="handleCycleValueInput" />
				</tn-form-item>
				<tn-form-item label="比例" prop="cycle_rate">
					<tn-input v-model="config.cycle_rate" type="digit" placeholder="请输入周期比例（1-100的正整数）" clearable
						@input="handleCycleRateInput" />
				</tn-form-item>
				<tn-form-item label="名称" prop="cycle_name">
					<tn-input v-model="config.cycle_name" placeholder="请输入名称（例如：T0）" clearable />
				</tn-form-item>
				<tn-form-item label="描述" prop="cycle_desc">
					<tn-input v-model="config.cycle_desc" type="textarea" placeholder="请输入描述信息" clearable />
				</tn-form-item>
			</tn-form>
			<view class="tn-flex-center">
				<tn-button size="lg" width="80vw" height="80" font-size="26" @click="submitForReview">确定修改</tn-button>
			</view>
		</view>
	</tn-popup>
</template>

<script setup>
	import {
		onMounted,
		ref,
	} from 'vue'
	import {
		getPeriodicConfigApi,
		setSwitchApi,
		editCycleApi
	} from "@/request/worktop/index.js"

	onMounted(() => {
		getPeriodicConfig()
	})

	const props = defineProps(['userId'])

	const isLoading = ref(true)
	const showPopup = ref(false)
	const modalRef = ref()
	const formRef = ref()
	const periodicList = ref([])
	const config = ref({
		id: props.userId,
		cyc_key: '',
		cycle_type: '',
		cycle_name: '',
		cycle_rate: '',
		cycle_value: '',
		cycle_desc: ''
	})
	// 规则
	const formRules = {
		cycle_value: [{
			required: true,
			message: '请输入账期',
			trigger: ['change', 'blur']
		}],
		cycle_name: [{
			required: true,
			message: '请输入周期名称',
			trigger: ['change', 'blur']
		}],
		cycle_desc: [{
			required: true,
			message: '请输入周期描述',
			trigger: ['change', 'blur']
		}],
		cycle_rate: [{
			required: true,
			message: '请输入周期比例',
			trigger: ['change', 'blur']
		}, {
			pattern: /^([1-9]\d?|100)$/,
			message: '请输入1-100之间的正整数',
			trigger: ['change', 'blur']
		}],
	}

	// 获取周期列表
	const getPeriodicConfig = () => {
		getPeriodicConfigApi(props.userId).then(res => {
			if (res.code == 0) {
				periodicList.value = res.data
			}
		}).catch(err => {
			uni.showToast({
				title: err.message,
				icon: 'none'
			})
		}).finally(() => {
			setTimeout(() => {
				isLoading.value = false
			}, 500)
		})
	}
	// 切换开关
	const changeActiveSwitch = (value, type, item) => {
		let obj = {
			id: props.userId,
			key: item.cycle_key,
			field: type,
			value: value
		}
		setSwitchApi(obj, 'update').then(res => {
			if (res.code == 0) {
				uni.showToast({
					title: res.message,
					success() {
						setTimeout(() => {
							getPeriodicConfig()
						}, 800)
					}
				})
			}
		}).catch(() => {
			uni.showToast({
				title: err.message,
				icon: 'none'
			})
		})
	}
	// 顶部按钮
	const btns = (type) => {
		modalRef.value?.showModal({
			title: '操作提示',
			content: `是否${type=='reload'?'重载':'清理'}配置`,
			showCancel: true,
			confirm() {
				setSwitchApi({
					id: props.userId
				}, type).then(res => {
					if (res.code == 0) {
						uni.showToast({
							title: res.message,
							success() {
								setTimeout(() => {
									getPeriodicConfig()
								}, 800)
							}
						})
					}
				}).catch(() => {
					uni.showToast({
						title: err.message,
						icon: 'none'
					})
				})
			}
		})
	}
	// 打开编辑弹窗
	const openPopup = (item) => {
		config.value = JSON.parse(JSON.stringify(item))
		showPopup.value = true
	}
	// 账期输入框改变
	const handleCycleValueInput = (value) => {
		config.value.cycle_name = `T${value}`
		config.value.cycle_desc = `账期${value}天，到账${config.value.cycle_rate}%`
	}
	// 比例输入框改变
	const handleCycleRateInput = (value) => {
		config.value.cycle_desc = `账期${config.value.cycle_value}天，到账${value}%`
	}
	// 确定修改
	const submitForReview = () => {
		formRef.value?.validate((valid) => {
			if (valid) {
				config.value.id = props.userId
				config.value.cyc_key = config.value.cycle_key
				editCycleApi(config.value).then(res => {
					if (res.code == 0) {
						uni.showToast({
							title: res.message,
							mask: true,
							success() {
								setTimeout(() => {
									showPopup.value = false
									getPeriodicConfig()
								}, 800)
							}
						})
					}
				}).catch(err => {
					uni.showToast({
						title: err.message,
						icon: 'none'
					})
				})
			} else {
				uni.showToast({
					title: '请检查必填项',
					icon: 'error',
				})
			}
		})
	}
</script>

<style scoped lang="scss">
</style>